package com.todo.auth.conf;

import com.todo.admin.common.base.SystemLoginUser;
import com.todo.auth.tool.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 继承OncePerRequestFilter类的话  可以确保只执行filter一次， 避免执行多次
 *
 * @author azhebuxing
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //TODO 这里是否需要针对C端用户和后台做缓存刷新操作
//        CurrentStaff currentStaff = tokenService.getSystemLoginUser(request);
//        if (currentStaff != null && AuthenticationUtils.getAuthentication() == null) {
//            tokenService.refreshStaffToken(currentStaff);
//            // 如果没有将当前登录用户放入到上下文中的话，会认定用户未授权，返回用户未登陆的错误
//            putCurrentLoginUserIntoContext(request, currentStaff);
//
//            log.debug("request process in jwt token filter. get login user id: {}", loginUser.getUserId());
//        }
        try {
            chain.doFilter(request, response);
        }catch (Exception ex){
            log.error("业务请求处理完成，遇到异常：打印异常信息", ex);
        }
    }


    private void putCurrentLoginUserIntoContext(HttpServletRequest request, SystemLoginUser loginUser) {
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(loginUser,
                null, loginUser.getAuthorities());
        authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authToken);
    }

}
